package com.example.httpdemo.mmkv;

import android.content.Context;
import android.util.Log;

import com.tencent.mmkv.MMKV;

public class MMKVHelper {

    private static MMKV mmkv;

    public static void init(Context context) {
        String rootDir = MMKV.initialize(context);
        Log.d("mmkv==" , rootDir);
        mmkv = MMKV.defaultMMKV();
    }

    /**
     * 泛型写入（支持基础类型）
     * @param key 存储键
     * @param value 支持类型：Boolean, Integer, Long, Float, Double, String, byte[]
     */
    public static <T> void put(String key, T value) {
        if (value == null) {
            mmkv.removeValueForKey(key);
            return;
        }

        if (value instanceof Boolean) {
            mmkv.encode(key, (Boolean) value);
        } else if (value instanceof Integer) {
            mmkv.encode(key, (Integer) value);
        } else if (value instanceof Long) {
            mmkv.encode(key, (Long) value);
        } else if (value instanceof Float) {
            mmkv.encode(key, (Float) value);
        } else if (value instanceof Double) {
            mmkv.encode(key, (Double) value);
        } else if (value instanceof String) {
            mmkv.encode(key, (String) value);
        } else if (value instanceof byte[]) {
            mmkv.encode(key, (byte[]) value);
        } else {
            Log.d("error","Unsupported data type: " + value.getClass());
        }
    }

    /**
     * 泛型读取（自动类型推断）
     * @param key 存储键
     * @param defaultValue 默认值（必须为非null，用于类型推断）
     * @return 与 defaultValue 相同类型的值
     */
    @SuppressWarnings("unchecked")
    public static <T> T get(String key, T defaultValue) {
        if (defaultValue == null) {
            Log.d("error","Default value cannot be null");
        }

        if (defaultValue instanceof Boolean) {
            return (T) Boolean.valueOf(mmkv.decodeBool(key, (Boolean) defaultValue));
        } else if (defaultValue instanceof Integer) {
            return (T) Integer.valueOf(mmkv.decodeInt(key, (Integer) defaultValue));
        } else if (defaultValue instanceof Long) {
            return (T) Long.valueOf(mmkv.decodeLong(key, (Long) defaultValue));
        } else if (defaultValue instanceof Float) {
            return (T) Float.valueOf(mmkv.decodeFloat(key, (Float) defaultValue));
        } else if (defaultValue instanceof Double) {
            return (T) Double.valueOf(mmkv.decodeDouble(key, (Double) defaultValue));
        } else if (defaultValue instanceof String) {
            return (T) mmkv.decodeString(key, (String) defaultValue);
        } else if (defaultValue instanceof byte[]) {
            return (T) mmkv.decodeBytes(key, (byte[]) defaultValue);
        } else {
            throw new IllegalArgumentException("Unsupported data type: " + defaultValue.getClass());
        }
    }

    // 删除键值对
    public static void remove(String key) {
        mmkv.removeValueForKey(key);
    }
}